// const { resolve } = require("path");

const SUCCESS = 'fulfilled'; //成功状态
const FAILURE = 'rejected';  //失败状态
const PENDING = 'pending';   //等待状态

function resolvePromise (value, resolve, reject) {
    if (typeof value === 'function' || typeof value === 'object') {
        try {
            let then = value.then;
            if (typeof then === 'function') {
                then.call(value, x => {
                    // resolve(x);
                    // 递归 兼容 外部 Promise 函数resolve(new Promise())传第一个promise 
                    resolvePromise(x, resolve, reject);
                }, err => {
                    reject(err);
                });
            } else {
                resolve(value)
            }
        } catch (error) {
            reject(error)
        }
    } else {
        resolve(value)
    }
}

class MyPromise {
    constructor (executor) {
        // executor 是new Promise((resolve, reject) => {}) 传递进来的函数
        this.status = PENDING; //初始状态
        this.value = undefined; //保存成功状态的数据，也就是resolve(data) 传递过来的data 保存起来
        this.reason = undefined; //保存失败状态的数据

        this.onFulfilledCallbacks = [];
        this.onRejectedCallbacks = [];
        
        //定义resolve函数 和 reject函数
        let resolve = value => {
            //当调用了此函数，说明是成功的，要把状态改成 成功状态
            //只有是 等待状态的时候才可以改变为成功或者失败，状态改变了不可在变
            if (this.status === PENDING) {
                this.status = SUCCESS;
                this.value = value;
                console.log('执行了resolve时，value的值是：'+this.value);
                /**
                 * 改变状态后，要执行 对应状态的回调函数
                 * 这部操作是为了处理 executor 函数中有异步时，会先先执行then 函数，此时status还是pending改变
                 * 所以在then 函数中也不会回调 成功或者失败的函数
                 */
                this.onFulfilledCallbacks.forEach(fn => fn())
            }
            
        }
        let reject = reason => {
            if (this.status === PENDING) {
                this.status = FAILURE;
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn => fn())
            }
            
        }
        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
        
    }

    //定义 then 函数
    then (onFulfilled, onRejected) {
        // console.log(onFulfilled, onRejected);
        // executor 函数中有异步操作时候， Promise对象 调用了 then() 会先执行。
        /**
         * executor 函数中有异步操作时候，外部 Promise对象 调用了 then() 会先执行,此时 status是pending
         * 而不是 等待 异步操作 调用了 resolve 函数后，才执行内部 的 then()
         * 所以需要把 内部 then 函数的 成功、失败回调函数保存下来
         */
        console.log('源码then函数，status的值是：'+this.status);

        return new MyPromise((resolve, reject) => {

            //等待状态时候 保存回调函数
            if (this.status === PENDING) {
                this.onFulfilledCallbacks.push(() => {
                    let v = onFulfilled(this.value);
                    resolvePromise(v, resolve, reject);
                })
                this.onRejectedCallbacks.push(() => {
                    let v = onRejected(this.reason);
                    resolvePromise(v, resolve, reject);
                })
            }

            if (this.status === SUCCESS) {
                let v = onFulfilled(this.value);
                resolvePromise(v, resolve, reject);
            }
            if (this.status === FAILURE) {
                let v = onRejected(this.reason);
                resolvePromise(v, resolve, reject);
            }

        })
        
        
    }
}

module.exports = MyPromise;